package com.sky.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: sky-take-out
 * @description:
 * @author: fmp
 * @create: 2023-04-09 15:10
 * @Version 1.0
 **/
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AddressBookMapper addressBookMapper;
    @Resource
    private ShopCartMapper shopCartMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private WebSocketService webSocketService;

    //分页查询历史订单
    @Override
    public PageResult selectHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
         ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
         //查询出单个的订单信息
        Page<Orders> ordersResult = orderMapper.selectOrderIds(ordersPageQueryDTO.getUserId());
        //将单个信息封装到返回对象vo中

        List<OrderVO> result = ordersResult.getResult().stream().map(new Function<Orders, OrderVO>() {
            @Override
            public OrderVO apply(Orders orders) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> orderDetailList = orderDetailMapper.selectOrdersDetail(orders.getId());
                orderVO.setOrderDetailList(orderDetailList);
                return orderVO;
            }
        }).collect(Collectors.toList());
        return PageResult.builder().total(ordersResult.getTotal()).records(result).build();
    }
    //用户下单
    @Transactional
    @Override
    public OrderSubmitVO submitOrders(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        Orders orders = new Orders();
        //将地址表中的数据传递给订单
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getFullAddress());
        orders.setConsignee(addressBook.getConsignee());
        //将接受到的数据传递给订单
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //设置订单其余参数
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(orders.UN_PAID);

        //实现订单添加
        orderMapper.submitOrders(orders);
        log.error("===========返回的id：{}",orders.getId());
        //通过userid查询购物车中内容
        List<ShoppingCart> shoppingCartList = shopCartMapper.selectShopCart(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        log.error("===d打印返回的购物车内容：{}",shoppingCartList.toString());
        if (Objects.isNull(shoppingCartList))
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        //订单详细信息添加 todo

        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(new Function<ShoppingCart, OrderDetail>() {
            @Override
            public OrderDetail apply(ShoppingCart shoppingCart) {
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
                orderDetail.setOrderId(orders.getId());
                log.info("=--------详细信息表中id：{}",orderDetail.getOrderId());
                return orderDetail;
            }
        }).collect(Collectors.toList());
        log.error("===打印订单详细西悉尼{}",orderDetailList.toString());
        //添加订单详细信息
        orderDetailMapper.InsetOrderDetail(orderDetailList);
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 用户请求支付功能
     *
     * @param ordersPaymentDTO 用于请求支付相关信息(订单号码/付款方式)
     * @return 微信支付基础信息VO
     */
    @Override
    public OrderPaymentVO pay(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        //获取本次请求支付订单的用户Id并查询用户信息
        Long userId = BaseContext.getCurrentId();

        User user = userMapper.selectUserById(userId);
        log.error("----------------ordersPaymentDTO.getOrderNumber():{}",ordersPaymentDTO.getOrderNumber());
        //调用微信支付接口生成预支付交易单
        /*JSONObject payInfoJsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //将订单编号传递给微信支付
                BigDecimal.valueOf(0.01),  //将订单金额传递给微信支付
                "苍穹外卖平台-订单",  //将收款标题传递给微信支付
                user.getOpenid()); //将付款人在微信的OPEN_ID传给微信支付
        if (Objects.nonNull(payInfoJsonObject.getString("code")) && "ORDERPAID".equals(payInfoJsonObject.getString("code")))
            throw new OrderBusinessException("订单已支付!");
        OrderPaymentVO orderPaymentVO = payInfoJsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setPackageStr(payInfoJsonObject.getString("package"));*/
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功功能(更改订单状态)
     *
     * @param orderNumber 订单编号
     */
    @SneakyThrows
    @Transactional
    @Override
    public void paySuccess(String orderNumber) {
        //根据当前用户Id与订单编号查询原始订单信息
        Orders orders = orderMapper.selectOrderByOrderNumberAndUserId(BaseContext.getCurrentId(), orderNumber);

        log.error("===========ordersid{}",orders.getId());
        log.error("===========orders{}",orders.toString());
        //封装新的订单更新条件对象并进行更新
        Orders newOrder = Orders.builder().id(orders.getId()) //订单Id(基于订单Id更新)
                .status(Orders.TO_BE_CONFIRMED) //修改订单状态为待接单(Orders中的静态常量)
                .payStatus(Orders.PAID) //修改订单支付状态为已支付(Orders中的静态常量)
                .checkoutTime(LocalDateTime.now()) //结账时间
                .build();
        //将购物车清空
        orderMapper.updateOrder(newOrder);
        shopCartMapper.CleanShoppingCart(BaseContext.getCurrentId());
        HashMap<Object, Object> infoMap = new HashMap<>();
        infoMap.put("type",1);
        infoMap.put("orderId",orders.getId());
        infoMap.put("content","订单号"+orderNumber);
        webSocketService.serverSendMessage2AllClient(JSONUtil.toJsonStr(infoMap));
    }
    //查询订单详情

    @Override
    public OrderVO getOrderDetails(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders =orderMapper.selectOrderById(id);
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrdersDetail(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }
    //用户取消订单
    @Override
    public void cancelOrder(Long orderId) {
        Orders orders = orderMapper.selectOrderById(orderId);
        if (orders == null && orders.getStatus()>Orders.CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        Orders buildOrder = Orders.builder().status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .cancelReason("取消订单")
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.updateOrder(buildOrder);
    }
    //再来一单
    @Override
    public void repetitionOrder(Long orderId) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrdersDetail(orderId);
        orderDetails.stream().map(new Function<OrderDetail, ShoppingCart>() {
            @Override
            public ShoppingCart apply(OrderDetail orderDetail) {
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCart.setUserId(BaseContext.getCurrentId());
                shopCartMapper.InsertShoppingCart(shoppingCart);
                return shoppingCart;
            }
        }).collect(Collectors.toList());

    }
}
